using Microsoft.AspNetCore.Mvc;
using community.Models;
using System.ComponentModel.DataAnnotations;
using Microsoft.EntityFrameworkCore;
using community.Data;

namespace community.Controllers
{
    /// <summary>
    /// 小区查询参数
    /// </summary>
    public class ComplexQueryDTO
    {
        /// <summary>
        /// 小区名称
        /// </summary>
        public string? Name { get; set; }

        /// <summary>
        /// 所属居委会ID
        /// </summary>
        public int? CommitteeId { get; set; }

        /// <summary>
        /// 每页显示数量，默认10条
        /// </summary>
        [Range(1, 100)]
        public int limit { get; set; } = 10;

        /// <summary>
        /// 当前页码，默认第1页
        /// </summary>
        [Range(1, int.MaxValue)]
        public int page { get; set; } = 1;
    }

    /// <summary>
    /// 创建/更新小区的数据模型
    /// </summary>
    public class ComplexDTO
    {
        /// <summary>
        /// 小区名称
        /// </summary>
        [Required(ErrorMessage = "小区名称不能为空")]
        [StringLength(100, ErrorMessage = "小区名称最多100个字符")]
        public string Name { get; set; }

        /// <summary>
        /// 小区地址
        /// </summary>
        [Required(ErrorMessage = "小区地址不能为空")]
        [StringLength(200, ErrorMessage = "小区地址最多200个字符")]
        public string Address { get; set; }

        /// <summary>
        /// 小区描述
        /// </summary>
        [Required(ErrorMessage = "小区描述不能为空")]
        public string Description { get; set; }

        /// <summary>
        /// 所属居委会ID
        /// </summary>
        [Required(ErrorMessage = "所属居委会不能为空")]
        public int CommitteeId { get; set; }
    }


    public class ComplexListDTO
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }
        public string Description { get; set; }
        public int CommitteeId { get; set; }
        public string CommitteeName { get; set; }

        public DateTime CreateTime { get; set; }
    }



    /// <summary>
    /// 小区管理接口
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class ComplexController : ControllerBase
    {
        private readonly ApplicationDbContext _context;

        public ComplexController(ApplicationDbContext context)
        {
            _context = context;
        }

        /// <summary>
        /// 获取小区列表（支持分页和条件筛选）
        /// </summary>
        /// <param name="query">查询参数</param>
        /// <returns>小区列表和总数</returns>
        /// <response code="200">成功获取小区列表</response>
        /// <response code="400">查询参数验证失败</response>
        [HttpGet]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        public async Task<IActionResult> GetComplexes([FromQuery] ComplexQueryDTO query)
        {
            var complexes = _context.Complex
                .Include(c => c.Committee)
                .AsQueryable();

            if (!string.IsNullOrEmpty(query.Name))
                complexes = complexes.Where(c => c.Name.Contains(query.Name));

            if (query.CommitteeId.HasValue)
                complexes = complexes.Where(c => c.CommitteeId == query.CommitteeId);

            var total = await complexes.CountAsync();

            var items = await complexes
                .Skip((query.page - 1) * query.limit)
                .Take(query.limit)
                .Select(c => new ComplexListDTO
                {
                    Id = c.Id,
                    Name = c.Name,
                    Address = c.Address,
                    Description = c.Description,
                    CommitteeId = c.CommitteeId,
                    CommitteeName = c.Committee.Name,
                    CreateTime = c.CreatedAt
                })
                .ToListAsync();

            return Ok(new
            {
                Total = total,
                Items = items
            });
        }
        /// <summary>
        /// 获取指定小区的详细信息
        /// </summary>
        /// <param name="id">小区ID</param>
        /// <returns>小区详细信息</returns>
        /// <response code="200">成功获取小区信息</response>
        /// <response code="404">指定ID的小区不存在</response>
        [HttpGet("{id}")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public async Task<IActionResult> GetComplex(int id)
        {
            var complex = await _context.Complex
                .Include(c => c.Committee)
                .Include(c => c.Houses)
                .FirstOrDefaultAsync(c => c.Id == id);

            if (complex == null)
                return NotFound();

            return Ok(complex);
        }

        /// <summary>
        /// 创建新小区
        /// </summary>
        /// <param name="dto">小区信息</param>
        /// <returns>新创建的小区信息</returns>
        /// <response code="201">成功创建小区</response>
        /// <response code="400">提供的数据无效</response>
        [HttpPost]
        [ProducesResponseType(StatusCodes.Status201Created)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        public async Task<IActionResult> CreateComplex(ComplexDTO dto)
        {
            // 检查居委会是否存在
            var committee = await _context.Committee.FindAsync(dto.CommitteeId);
            if (committee == null)
                return BadRequest("指定的居委会不存在");

            var complex = new Complex
            {
                Name = dto.Name,
                Address = dto.Address,
                Description = dto.Description,
                CommitteeId = dto.CommitteeId,
                CreatedAt = DateTime.UtcNow,
                UpdatedAt = DateTime.UtcNow
            };

            _context.Complex.Add(complex);
            await _context.SaveChangesAsync();

            return CreatedAtAction(nameof(GetComplex), new { id = complex.Id }, "创建成功");
        }

        /// <summary>
        /// 更新小区信息
        /// </summary>
        /// <param name="id">小区ID</param>
        /// <param name="dto">更新的小区信息</param>
        /// <returns>更新后的小区信息</returns>
        /// <response code="200">成功更新小区信息</response>
        /// <response code="400">提供的数据无效</response>
        /// <response code="404">指定ID的小区不存在</response>
        [HttpPut("{id}")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public async Task<IActionResult> UpdateComplex(int id, ComplexDTO dto)
        {
            var complex = await _context.Complex.FindAsync(id);
            if (complex == null)
                return NotFound();

            // 检查居委会是否存在
            var committee = await _context.Committee.FindAsync(dto.CommitteeId);
            if (committee == null)
                return BadRequest("指定的居委会不存在");

            complex.Name = dto.Name;
            complex.Address = dto.Address;
            complex.Description = dto.Description;
            complex.CommitteeId = dto.CommitteeId;
            complex.UpdatedAt = DateTime.UtcNow;

            await _context.SaveChangesAsync();
            return Ok(complex);
        }

        /// <summary>
        /// 删除小区
        /// </summary>
        /// <param name="id">小区ID</param>
        /// <returns>无内容</returns>
        /// <response code="204">成功删除小区</response>
        /// <response code="404">指定ID的小区不存在</response>
        [HttpDelete("{id}")]
        [ProducesResponseType(StatusCodes.Status204NoContent)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public async Task<IActionResult> DeleteComplex(int id)
        {
            var complex = await _context.Complex.FindAsync(id);
            if (complex == null)
                return NotFound();

            _context.Complex.Remove(complex);
            await _context.SaveChangesAsync();

            return NoContent();
        }

        /// <summary>
        /// 获取小区房屋列表
        /// </summary>
        /// <param name="id">小区ID</param>
        /// <returns>房屋列表</returns>
        /// <response code="200">成功获取房屋列表</response>
        /// <response code="404">小区不存在</response>
        [HttpGet("{id}/houses")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public async Task<IActionResult> GetComplexHouses(int id)
        {
            var complex = await _context.Complex
                .Include(c => c.Houses)
                .FirstOrDefaultAsync(c => c.Id == id);

            if (complex == null)
            {
                return NotFound(new { message = "小区不存在" });
            }

            return Ok(complex.Houses);
        }
    }
} 